<?php

namespace App\Repositories;

use App\Models\Tag;
use App\Models\TagMapping;

class TagRepository
{
    public function getTagByObject($object_id, $object_type)
    {
        $mapping = TagMapping::query()
            ->with('tag')
            ->where('object_type', $object_type)
            ->where('object_id', $object_id)
            ->get();

        if ($mapping->count()) {
            // return $mapping[0]->tag;
            return $mapping->toArray();
        }

        return [];
    }

    /**
     * 获取Tag
     *
     * @param string $objectType
     * @param array $objectIds
     * @return array
     */
    public function forObject(string $objectType, array $objectIds)
    {
        $list = TagMapping::where('object_type', '=', $objectType)
            ->whereIn('object_id', $objectIds)
            ->select('tag_id', 'object_id')
            ->get()
            ->toArray();
        if (count($list) > 0) {
            $tagIds = [];
            foreach ($list as $item) {
                $tagIds[] = $item['tag_id'];
            }
            $tags = Tag::whereIn('id', $tagIds)
                ->select('id', 'title')
                ->get()
                ->toArray();
            $tagObj = [];
            foreach ($tags as $item) {
                $tagObj[$item['id']] = $item['title'];
            }
            // dd($list, $tagObj);
            foreach ($list as $k => $item) {
                $list[$k]['tag'] = $tagObj[$item['tag_id']];
            }
        }
        return $list;
    }

    /**
     * 覆盖式重新保存志愿者关注方向
     *
     * @param $tagIds
     * @param $contactId
     *
     * @return bool
     */
    public function reWriteContactFollow($tagIds, $contactId)
    {
        MyFollow::query()
            ->where('contact_id', $contactId)
            ->delete();

        foreach ($tagIds as $tagId) {
            $insertData = [
                'contact_id' => $contactId,
                'tag_id' => $tagId,
            ];

            MyFollow::create($insertData);
        }
        return true;
    }



    public function getAllFollowTags()
    {
        return $this->getByType(Tag::FOLLOW_TYPE);
    }

    private function getByType($type, $order = false)
    {
        return Tag::query()
            ->where('type', $type)
            ->when($order, function ($query) use ($order) {
                return $query->orderByRaw($order);
            })
            ->get();
    }

    public function getTags($filter,$type = Tag::ACTIVITY_TYPE)
    {
        return  Tag::query()
                    ->where('type',$type)
                    ->when($filter['title'],function($query) use ($filter){
                        $query->where('title','like','%'.$filter['title'].'%');
                    })
                    ->orderBy('created_at','desc')
                    ->paginate(self::PAGE_SIZE);
    }

}
